﻿// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
// Copyright (c) 2011, Dr. Masroor Ehsan
// All rights reserved.
// 
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the author nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
// 
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// 
// $Author: masroore@gmail.com $
// $Id: HapQuotesParsingStage.cs 39 2011-10-23 07:44:27Z masroore@gmail.com $
// $Rev: 39 $
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
using MaxTrader.Core.Pipeline;
using MaxTrader.QuotesParser.Core;
using MaxTrader.StockQuotesParser.Pipeline;

namespace MaxTrader.IDQuotesParser.Dse.HAP
{
    public sealed class HapQuotesParsingStage : IStage
    {
        private readonly QuoteFieldColumnMap _map;

        public HapQuotesParsingStage()
        {
            _map = new QuoteFieldColumnMap();

            //#  Trading Code  LTP*  High  Low  Close Price  YCP  Change  Trade  Volume            
            _map.AddSearchPattern(StockQuoteField.Symbol, @"\bcode\b");
            _map.AddSearchPattern(StockQuoteField.High, @"\bhigh\b");
            _map.AddSearchPattern(StockQuoteField.Low, @"\blow\b");
            _map.AddSearchPattern(StockQuoteField.Close, @"\bclose\b");
            _map.AddSearchPattern(StockQuoteField.Ltp, @"\bltp\b");
            _map.AddSearchPattern(StockQuoteField.PrevClose, @"\bycp\b");
            _map.AddSearchPattern(StockQuoteField.Change, @"\bchange\b");
            _map.AddSearchPattern(StockQuoteField.Trades, @"\btrade\b");
            _map.AddSearchPattern(StockQuoteField.Volume, @"\bvolume\b");
        }

        #region IStage Members

        public void Execute(IPipelineContext context)
        {
            var ctx = (StockQuotesParserContext) context;
            var doc = new HtmlDocument();

            try
            {
                doc.LoadHtml(ctx.SanitizedData);
                bool tableHeaderProcessed = false;

                var nodes = doc.DocumentNode.SelectNodes(@"//body/div/table/tr");

                if (nodes != null)
                {
                    foreach (var link in nodes)
                    {
                        if (!tableHeaderProcessed)
                        {
                            ProcessTableHeader(link.SelectNodes("td"));
                            tableHeaderProcessed = true;
                            continue;
                        }

                        ProcessTableRow(link.SelectNodes("td"), ctx);
                    }
                }
            }
            catch (Exception exc)
            {
                ctx.Errors.Add(new QuotesParserError(ctx.Parser, exc.Message));
            }
        }

        #endregion

        private void ProcessTableHeader(IEnumerable<HtmlNode> nodes)
        {
            var index = 0;
            foreach (var column in nodes)
            {
                DiscoverFieldIndices(column.InnerText.Trim(), index);
                index++;
            }
        }

        private void ProcessTableRow(HtmlNodeCollection nodes, StockQuotesParserContext context)
        {
            if (nodes != null)
            {
                var discoveredFields = _map.GetPriceFields();
                var price = new RawStockQuote();

                foreach (var field in discoveredFields)
                {
                    var index = _map.GetColumnIndex(field);
                    var data = nodes[index].InnerText.Trim();
                    price.SetData(field, data);
                }

                context.RawQuotes.Add(price);
            }
        }

        private void DiscoverFieldIndices(string rawData, int index)
        {
            foreach (var pattern in _map.GetSearchPatterns())
            {
                if (Regex.IsMatch(rawData, pattern, RegexOptions.IgnoreCase))
                {
                    _map.SetColumnIndex(_map.PriceFieldForsearchPattern(pattern), index);
                    return;
                }
            }

            return;
        }
    }
}